package io.sunny.platform.backend.security.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Date;
import java.util.UUID;

/**
 * @Author SUNNY
 * @Date 2025/7/23 14:37
 * @PackageName: io.sunny.platform.security.auth.utils
 * @Description: 生成与验证 JWT
 * @Version 1.0
 */
@Component
public class JwtUtils {
    @Value("${jwt.secret:1234567890BCDEDIT}")
    private String secret;
    @Value("${jwt.access-token-expire:600}")
    private long accessTokenExpireSeconds;
    @Value("${jwt.refresh-token-expire:3600}")
    private long refreshTokenExpireSeconds;
    private Key key;

    @PostConstruct
    public void init() {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] keyBytes = sha256.digest(secret.getBytes(StandardCharsets.UTF_8));
            this.key = Keys.hmacShaKeyFor(keyBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成 JWT Token
     */
    public String generateToken(String username, boolean isRefreshToken) {
        long nowMillis = System.currentTimeMillis();
        long expire = isRefreshToken ? refreshTokenExpireSeconds : accessTokenExpireSeconds;

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(nowMillis))
                .setExpiration(new Date(nowMillis + expire * 1000))
                .setId(UUID.randomUUID().toString())  // 设置唯一 tokenId
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 解析 token
     */
    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
